package Chapter08.encap;

/**
 * @author 杨森
 * @date 2022年09月20日 15:31
 */
public class Encapsulation01 {
    public static void main(String[] args) {
        final Person person = new Person();
        person.setName("jack");
        person.setAge(30);
        person.setSalary(1000);
        System.out.println(person.toString());

        final Person smith = new Person("smith", 3000, 5050);
        System.out.println(smith.toString());
    }
}

class Person {
    public String name;
    private int age;
    private double salary;

    public Person(){

    }

    public Person(String name, int age, double salary) {
//        this.name = name;
//        this.age = age;
//        this.salary = salary;
        setName(name);
        setAge(age);
        setSalary(salary);
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Person{");
        sb.append("name='").append(name).append('\'');
        sb.append(", age=").append(age);
        sb.append('}');
        return sb.toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if (name.length() >= 2 && name.length() <= 6){
            this.name = name;
        }else {
            System.out.println("名字的长度需要在2-6个字符之间");
            this.name = "无名人";
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >= 1 && age <= 120) {
            this.age = age;
        } else {
            System.out.println("输入的年龄需要在1-120岁之间");
            this.age = 18;//给定一个默认年龄
        }
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}
